package com.shrio.test.controls;

import com.shrio.test.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by joychen on 2018/2/26.
 */
@RequestMapping("/web_api")
@Controller
public class UserControl {

    @Autowired
    UserService userService;

    private static final Logger logger = LoggerFactory
            .getLogger(UserControl.class);

    @RequestMapping("/logon")
    public String logon(@RequestParam("username") String username, @RequestParam("password") String password) {

//        if ("joychen".equals(username) && "123456".equals(password)) {
//            System.out.println("登录成功！");
//
//            return "home";
//        }

        // 用户shiro来验证
        //1.获取Subject类型的实例
        //2.判断用户是否已经登录
        //3.使用UsernamePasswordToken对象封装用户名及密码
        //4.使用Subjet实例中的login(token)

        //1.创建Subjet对象
        Subject currentUser = SecurityUtils.getSubject();
        //2.判断当前用户是否登录
        if (currentUser.isAuthenticated() == false) {
            //3.将用户名及密码封装到UserNamePasswordToken
            try {
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                currentUser.login(token);
            } catch (UnknownAccountException unAcex) {
                logger.info("账号不存在!");
                System.out.println("账号不存在!");
                return "login";
            } catch (IncorrectCredentialsException incEx) {
                System.out.println("密码错误!");
                return "login";
            } catch (AuthenticationException auex) {
                System.out.println("用户名密码不正确!");
                return "login";
            }

        }
        return "home";
    }

    @RequestMapping("/logout")
    public String logout() {



        return "login";
    }

}
